package me.hyman.testcustomview.pullToLoadDetail;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

/**
 * Created by Hyman on 2016/9/18.
 */
public class MyScrollView extends ScrollView {

    private MyScrollListener myScrollListener;

    public MyScrollView(Context context) {
        super(context);
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setScrollListener(MyScrollListener myScrollListener) {
        this.myScrollListener = myScrollListener;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        if(ev.getAction() == MotionEvent.ACTION_MOVE) {

            if(myScrollListener != null) {

                int childHeight = getChildAt(0).getHeight();
                int height = getHeight();
                int scrollY = getScrollY();

                //childHeight = height + scrollY的最大值
                //Logger.e("childHeight: " + childHeight + ", height: " + height + ", scrollY: " + scrollY);

                myScrollListener.onScroll(scrollY);

                if(scrollY + height >= childHeight || childHeight <= height) {
                    myScrollListener.onScrollBottom(true);
                } else {
                    myScrollListener.onScrollBottom(false);
                }

                if(scrollY == 0) {
                    myScrollListener.onScrollTop();
                }
            }
        }

        requestDisallowInterceptTouchEvent(false);

        //Logger.d("MyScrollVIew: " + super.onTouchEvent(ev));

        return super.onTouchEvent(ev);
    }

    public interface MyScrollListener {
        void onScrollTop();
        void onScrollBottom(boolean atBottom);
        void onScroll(int scrollY);
    }
}
